import React from 'react'
import './countdown.less'

/**
 * @desc 倒计时组件
 */
class Countdown extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      currentTime: [0, 0, 0, 0] // 当前时间
    }
    this.timer = null
    this.isCounting = false // 是否在计时中
  }

  /**
   * @desc 清除计时器
   */
  componentWillUnmount() {
    this.timer && clearInterval(this.timer)
    this.timer = null
  }

  /**
   * @desc 计算当前时间秒数
   */
  sumTime() {
    let mul = [60 * 10, 60, 10, 1] // 倍数
    let time = this.state.currentTime.reduce((acc, cur, i) => {
      return acc + cur * mul[i]
    }, 0)

    return time
  }

  /**
   * @desc 将时间解析成数组
   * @param sumSec
   */
  parseTime(sumSec) {
    let min = Math.floor(sumSec / 60)
    let sec = sumSec % 60

    let time = (this.addPreZero(min) + this.addPreZero(sec)).split('')
    return time
  }

  /**
   * @desc 自动补零
   * @param num
   */
  addPreZero(num) {
    return num < 10 ? '0' + num : num
  }

  /**
   * @desc 时间设置处理函数
   * @param timeIndex 时间数组索引
   */
  handleSetTime(timeIndex) {
    if (!this.isCounting) {
      let currentTime = this.state.currentTime
      ++currentTime[timeIndex]
      if (timeIndex === 0 || timeIndex === 2) {
        currentTime[timeIndex] > 5 ? (currentTime[timeIndex] = 0) : void 0
      }
      if (timeIndex === 1 || timeIndex === 3) {
        currentTime[timeIndex] > 9 ? (currentTime[timeIndex] = 0) : void 0
      }

      this.setState({
        currentTime
      })
    }
  }

  handleStart() {
    let remainTime = this.sumTime()
    if (remainTime) {
      this.timer = setInterval(() => {
        --remainTime
        let currentTime = this.parseTime(remainTime)
        this.setState({
          currentTime
        })
        if (remainTime === 0) {
          clearInterval(this.timer)
          this.timer = null
        }
      }, 1000)
    }
  }

  render() {
    let time = this.state.currentTime.map((t, i) => {
      return (
        <li key={i} onClick={e => this.handleSetTime(i, e)}>
          {t}
        </li>
      )
    })
    return (
      <div id="countdown">
        <ul className="time">{time}</ul>
        <div className="start" onClick={e => this.handleStart(e)}>
          start!
        </div>
      </div>
    )
  }
}

export default Countdown
